package com.briup.ch02;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/11/6
 * @Description:
 */
public class TruncationTest {
    public static void main(String[] args) throws SQLException {
        String dirverClass="com.mysql.cj.jdbc.Driver";
        String url="jdbc:mysql://localhost:3306/briup";
        String username="briup";
        String password="briup";
        Connection conn = null;
        PreparedStatement pstmt = null;
        List<TUser> list = new ArrayList<>();
        list.add(new TUser("Jerry","123456"));
        list.add(new TUser("Mike","123456"));
        list.add(new TUser("Lily","123456"));
        list.add(new TUser("Tom","123456"));
        int count=0;
        try {
            //1.注册驱动
            Class.forName(dirverClass);
            //2.获得数据库连接
            conn= DriverManager.getConnection(url,username,password);
            //开启事务,要么成功，要么不成功
            conn.setAutoCommit(false);
            //3.获得prepareStatement对象
            pstmt = conn.prepareStatement("insert into user(name,password) values(?,?)");

            for(TUser user:list){
                //4.设置指
                pstmt.setString(1,user.getName());
                pstmt.setString(2,user.getPassword());
                //5.执行SQL语句
                int num=pstmt.executeUpdate();
                //6.处理结果集 ---4，5，6会被重复执行
                System.out.println("插入成功！"+num);
                count++;
            }
            //提交事务
            conn.commit();
            System.out.println("一共插入了"+count+"条数据！");
        } catch (Exception e) {
            try {
                conn.rollback();
                System.out.println("回滚！" + count + "条数据！");
            }catch(SQLException s){
                s.printStackTrace();
            }
            e.printStackTrace();
       } finally{
            //7.关闭资源
            try {
                if(pstmt!=null){
                    pstmt.close();
                }
                if(conn!=null){
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
class TUser{
    private String name;
    private String password;
    public TUser(String name,String password){
        this.name = name;
        this.password = password;
    }
    public String getName(){
        return name;
    }
    public String getPassword(){
        return password;
    }
}